import fs from 'fs-extra';
import path from "path";
import { toolchain } from "../../toolchain.js";
import { BaseTask, TaskResult } from "./BastTask.js";

export class DynamicRemoveTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        const drs = toolchain.params.channelCfg.dynamicRemoves;
        if (drs) {
            await this.executeRemove(drs[toolchain.option.platform]);
            if (toolchain.option.platform == 'WebGL') {
                await this.executeRemove(drs[`${toolchain.option.platform}_${toolchain.option.webglRuntime}`]);
            }
        }

        return { success: true, errorCode: 0 };
    }

    private async executeRemove(dr: string[] | undefined) {
        if (dr != null) {
            for (const d of dr) {
                const dp = path.join(toolchain.params.workSpacePath, d);
                if (!fs.existsSync(dp)) {
                    throw 'dynamic remove failed: ' + dp;
                }
                const s = await fs.stat(dp);
                if (s.isDirectory()) {
                    await fs.rm(dp, { recursive: true, force: true });
                } else {
                    await fs.unlink(dp);
                }
                await fs.unlink(dp + '.meta');
            }
        }
    }
}
